﻿using AutoMapper;


using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Writer.API.Application.Commends;
using MediatR;
using System;
using Yitter.IdGenerator;

namespace B.S.Traceability.Writer.API.Application.CommendHandlers
{
    public class CreateProductsCommendHandlers : IRequestHandler<CreateProductsCommends, APIResult<Products>>
    {

        private readonly IBaseRepository<Products> productsRepository;
        private readonly IMapper mapper;

        public CreateProductsCommendHandlers(IBaseRepository<Products> productsRepository, IMapper mapper)
        {
            this.productsRepository = productsRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加生产信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<Products>> Handle(CreateProductsCommends request, CancellationToken cancellationToken)
        {
            APIResult<Products> result = new APIResult<Products>();
        
            var products = mapper.Map<Products>(request);
              Random rand = new Random();
              products.CreateName=request.CreateName;
              products.CreateTime=DateTime.Now;
            products.UpdateTime = null;
            products.UpdateName = "";
            products.IsDel = false;
            products.Productionnumber="SC"+YitIdHelper.NextId();
       
            var product = productsRepository.GetAllAsync().Result.FirstOrDefault(p => p.ShoopId == request.ShoopId);
            if (product != null)
            {
                result.Code = APIEnum.商品名称重复;
                result.Msg = APIEnum.商品名称重复.ToString();
            }
            else
            {
                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
                await productsRepository.Add(products);
            }
          
            return await Task.FromResult(result);
        }
    }
}
